package com.uinnova.product.eam.init.cassso;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uinnova.product.eam.service.asset.BmConfigSvc;
import lombok.extern.slf4j.Slf4j;
import org.jasig.cas.client.validation.Cas30ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description: cas单点登录配置
 * @author: LiMG
 * @create: 2024-05-28 16:37:41
 **/
@Slf4j
@Configuration
@ConditionalOnProperty(name = "monet.login.loginMethod", havingValue = "guotouiam")
public class CASConfig {

    @Autowired
    private BmConfigSvc bmConfigSvc;

    /**
     * 国投用户key前缀
     */
    public static final String GUOTOU_USER_KEY_PREFIX = "EA:GUOTOU:USER:";

    /**
     * 票据校验Bean
     */
    @Bean
    public TicketValidator ticketValidator() {
        String config = bmConfigSvc.getConfigType("IAM_CAS_LOGIN_CONFIG");
        if (StrUtil.isEmpty(config)) {
            log.error("无法获取视图配置中的国投IAM单点登录配置项");
            return null;
        }
        JSONObject json = JSON.parseObject(config);
        String casServerUrl = json.getString("casServerUrl");
        if (StrUtil.isEmpty(casServerUrl)) {
            log.error("无法获取cas服务地址，初始化登录票据验证服务失败");
            return null;
        }
        return new Cas30ServiceTicketValidator(casServerUrl);
    }

    @Bean
    public CASLogoutListener singleLogout() {
        JSONObject config = getCasLoginConfig();
        if (null != config) {
            final CASLogoutListener logoutListener = new CASLogoutListener(config);
            // 运行登出监听
            logoutListener.run();
            return logoutListener;
        }
        return null;
    }

    private JSONObject getCasLoginConfig() {
        String config = bmConfigSvc.getConfigType("IAM_CAS_LOGIN_CONFIG");
        if (StrUtil.isEmpty(config)) {
            log.error("无法获取视图配置中的国投IAM单点登录配置项");
            return null;
        }
        return JSON.parseObject(config);
    }

}
